package com.cxb;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.*;
import com.cxb.adapter.WifiAdapter;
import com.cxb.entity.AccessPoint;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.WifiUtils;

import java.util.Iterator;
import java.util.List;


/**
 * Author jerry
 * date: 2016/8/5.
 */
public class WifiSettingsActivity extends BaseActivity implements AdapterView.OnItemClickListener{
	private static final String TAG = "wifi_mode";
	//下面两个ACTION 被SDK隐藏了，自己定义一下
	public static final String CONFIGURED_NETWORKS_CHANGED_ACTION = "android.net.wifi.CONFIGURED_NETWORKS_CHANGE";
	public static final String LINK_CONFIGURATION_CHANGED_ACTION = "android.net.wifi.LINK_CONFIGURATION_CHANGED";
	/** 连接超时:30S */
	private static final long CONNECT_TIME_OUT = 30 * 1000;
//	private static final int WIFI_RESCAN_INTERVAL_MS = 6 * 1000;
	//========================= UI ===============================================
	private TextView mTVSSID;
	private TextView mTip;
	private EditText mETPwd;
	private CheckBox mCBShowPwd;
	private ImageButton mBtnSwitch;
	private ImageView mIVLoading;
	private RotateAnimation mLoadingAnimation;
	private Dialog mConnectDialog;
	private ListView mWifiListView;
	private List<AccessPoint> mAccessPoints;
	private WifiAdapter mWifiAdapter;
	private AccessPoint mSelectPoint;
	/** 最后一次连接上的wifi点 */
	private AccessPoint mLastPoint;
	private AccessPoint mConnectingPoint;
	private View mHeadView;//显示连接上的wifi
	private boolean mInitHead = false;
	private static final int DISCONNECT = 0;
	private static final int CONNECT = 1;
	//==============================================================================
	private BroadcastReceiver mReceiver;
	private WifiManager mWifiManager;
	private IntentFilter mfilter;
	private Handler mHandler = new Handler();
	private SharedPreferencesUtils mSharedPreferencesUtils;
//	private Scanner mScaner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifi_setting_layout);
		mLoadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.loading);
		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		mSharedPreferencesUtils = new SharedPreferencesUtils(this);
//		mScaner = new Scanner();
		initViews();
		initBroadcastReceiver();

	}

	@Override
	protected void onPause() {
		super.onPause();
//		mScaner.pause();
		unregisterReceiver(mReceiver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(mReceiver, mfilter);
	}

	private void initViews(){
//		mBtnBack = (ImageButton) findViewById(R.id.btn_goback);
		mBtnSwitch = (ImageButton) findViewById(R.id.btn_switch);
		mWifiListView = (ListView) findViewById(R.id.wifi_list);
		mIVLoading = (ImageView) findViewById(R.id.iv_loading);
		mTip = (TextView) findViewById(R.id.wifi_not_open);

		mHeadView = LayoutInflater.from(this).inflate(R.layout.wifi_header, null, false);
	//	mHeadView.setOnClickListener(onHeaderClick);

		if(mConnectDialog == null){
			initConnectDialog();
		}

		mTVSSID = (TextView) mConnectDialog.findViewById(R.id.tv_ssid);
		mETPwd = (EditText) mConnectDialog.findViewById(R.id.et_password);
		mCBShowPwd = (CheckBox) mConnectDialog.findViewById(R.id.cb_show_password);
		mCBShowPwd.setOnCheckedChangeListener(mOnCheckBoxClickListener);

		mBtnSwitch.setOnClickListener(mOnBtnClick);
		updateSwitchButton(mWifiManager.isWifiEnabled());

		if(!mWifiManager.isWifiEnabled()){
			//wifi 没有打开的话不显示listview
			mWifiListView.setVisibility(View.GONE);
			mTip.setVisibility(View.VISIBLE);
		}else {
			mTip.setVisibility(View.GONE);
			try{
				List<ScanResult> points = mWifiManager.getScanResults();
				mAccessPoints = WifiUtils.parseAccesspoint(points);
				Log.e(TAG, "进入setting wifi 发现可用点:"+mAccessPoints.size());
				if(mAccessPoints.size() != 0){
					WifiInfo info = WifiUtils.getCurrentWifiInfo(this);
					if(info != null){
						mLastPoint = new AccessPoint(info);
						Log.e(TAG, "wifi 已经连接了:"+mLastPoint.toString());
						//删除列表中已经连接上的点
						filterConnectedPoint(mAccessPoints, mLastPoint);
						//已经连接上的点，显示在ListView的顶部，(页眉)
						addListHeader(mLastPoint);
						updateStatus(getString(R.string.wifi_connected));
					}
					initListView(mAccessPoints);
					mWifiListView.setVisibility(View.VISIBLE);
				}else {
					//没有可用的信息，不显示listView
					mWifiListView.setVisibility(View.GONE);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
		}
		mWifiListView.setOnItemClickListener(this);
	}

	private void initListView(List<AccessPoint> accessPoints){
		mWifiAdapter = new WifiAdapter(this, accessPoints);
		mWifiListView.setAdapter(mWifiAdapter);
	}
	private View.OnClickListener onHeaderClick = new View.OnClickListener(){
		@Override
		public void onClick(View view) {

		}
	};

	private CheckBox.OnCheckedChangeListener mOnCheckBoxClickListener = new CheckBox.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
									 boolean isChecked) {
			if (mCBShowPwd.isChecked()) {
				// 文本正常显示
				mETPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				Editable etable = mETPwd.getText();
				Selection.setSelection(etable, etable.length());
			} else {
				// 文本以密码形式显示
				mETPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				// 下面两行代码实现: 输入框光标一直在输入文本后面
				Editable etable = mETPwd.getText();
				Selection.setSelection(etable, etable.length());
			}
		}
	};

	private void initConnectDialog(){
		View contentView = LayoutInflater.from(this).inflate(R.layout.wifi_connect_dialog, null);
		mConnectDialog = new Dialog(this, R.style.dialog);
		Window window = mConnectDialog.getWindow();
		WindowManager.LayoutParams params = window.getAttributes();
		params.width = WindowManager.LayoutParams.WRAP_CONTENT;
		params.width = WindowManager.LayoutParams.WRAP_CONTENT;
		window.setAttributes(params);
		mConnectDialog.setContentView(contentView);
		mConnectDialog.setCanceledOnTouchOutside(true);
		mConnectDialog.findViewById(R.id.tv_confirm).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						int oprator = (Integer) v.getTag();
						mConnectDialog.dismiss();
						if(oprator == WifiSettingsActivity.DISCONNECT){
							disconnect();
						}else if(oprator == WifiSettingsActivity.CONNECT){
							String pwd = mETPwd.getText().toString().trim();
							if(TextUtils.isEmpty(pwd) || pwd.length() < 8){
								Toast.makeText(WifiSettingsActivity.this, R.string.input_right_wifi_password, Toast.LENGTH_SHORT).show();
								return;
							}
							mSelectPoint.setPwd(pwd);
							connectWifi(mSelectPoint);
							mSelectPoint = null;
						}

					}
				});
		mConnectDialog.findViewById(R.id.tv_cancel).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						mConnectDialog.dismiss();
						mSelectPoint = null;
					}
				});
	}
	private View.OnClickListener mOnBtnClick = new View.OnClickListener(){
		@Override
		public void onClick(View view) {
			int id = view.getId();
			switch (id){
				case R.id.btn_goback:{
					WifiSettingsActivity.this.finish();
					break;
				}

				case R.id.btn_switch:{
					toggleWifi();
					break;
				}
			}

		}
	};

	private void updateSwitchButton(boolean isWifiEnable){
		if(isWifiEnable){
			mBtnSwitch.setImageResource(R.drawable.sw_on);
		}else {
			mBtnSwitch.setImageResource(R.drawable.sw_off);
		}
	}

	private void toggleWifi(){
		boolean enable = mWifiManager.isWifiEnabled();
		WifiUtils.enableWifi(!enable);
		if(!enable){
			mIVLoading.setVisibility(View.VISIBLE);
			mIVLoading.startAnimation(mLoadingAnimation);
			updateSwitchButton(true);
			mTip.setVisibility(View.GONE);
		}
	}

	private void initBroadcastReceiver(){
		mfilter = new IntentFilter();
		mfilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		mfilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		mfilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
		mfilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
		mfilter.addAction(WifiSettingsActivity.CONFIGURED_NETWORKS_CHANGED_ACTION);
		mfilter.addAction(WifiSettingsActivity.LINK_CONFIGURATION_CHANGED_ACTION);
		mfilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		mfilter.addAction(WifiManager.RSSI_CHANGED_ACTION);

		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				handleEvent(intent);
			}
		};

	}

	private void handleEvent(Intent intent) {
		String action = intent.getAction();
		if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
			updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
											   WifiManager.WIFI_STATE_UNKNOWN));
		} else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
			Log.e(TAG, "广播:扫描成功");
//			WifiSettingsActivity.CONFIGURED_NETWORKS_CHANGED_ACTION.equals(action)
//			WifiSettingsActivity.LINK_CONFIGURATION_CHANGED_ACTION.equals(action)
			if(mIVLoading.getAnimation() != null){
				mIVLoading.getAnimation().cancel();
				mIVLoading.clearAnimation();
				mIVLoading.setVisibility(View.GONE);
			}
			updateAccessPoints();
		} else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
			NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
					WifiManager.EXTRA_NETWORK_INFO);
			if(info != null){
				boolean connect = info.isConnected();
				int type = info.getType();
				if(connect && type == ConnectivityManager.TYPE_WIFI){
					WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
					if(TextUtils.isEmpty(wifiInfo.getBSSID())|| wifiInfo.getBSSID().equals("00:00:00:00:00:00")){
						Log.e(TAG, "无效的wifi连接点:"+"SSID="+wifiInfo.getSSID() + " BSSID="+wifiInfo.getBSSID());
						mLastPoint = null;
						updateWifiList(null);
						return;
					}
					mLastPoint = new AccessPoint(wifiInfo);
					updateWifiList(mLastPoint);
					updateStatus(getString(R.string.wifi_connected));
					if(mLastPoint.equals(mConnectingPoint)){
						Log.e(TAG, "连接到指定的wifi@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
						saveWifiPassword(mConnectingPoint.BSSID, mConnectingPoint.pwd);
					}else if(mConnectingPoint != null){
						Log.e(TAG, "连接"+mConnectingPoint.SSID+"失败后，自动连接到:"+mLastPoint.SSID);
					}else if(mConnectingPoint == null){
						Log.e(TAG, "原生Setting自动连接到:"+mLastPoint.SSID);
					}
					mConnectingPoint = null;
				}else if(connect && type == ConnectivityManager.TYPE_MOBILE){
					Log.e(TAG, "连上了移动网络");
				}
			}

		} else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
			//Toast.makeText(WifiSettingsActivity.this, "信号变了:"+mWifiManager.getConnectionInfo().getSSID(), Toast.LENGTH_LONG).show();
			//Log.e(TAG, "当前连接SSID:"+mWifiManager.getConnectionInfo().getSSID());
		}
	}



	private void updateWifiState(int state) {
		switch (state) {
		case WifiManager.WIFI_STATE_ENABLED:
			updateSwitchButton(true);
			mTip.setVisibility(View.GONE);
//			mScaner.resume();
			Log.e(TAG, "wifi 已经打开");
			return;

		case WifiManager.WIFI_STATE_ENABLING:
			Log.e(TAG, "wifi 打开中。。。。。");
			break;

		case WifiManager.WIFI_STATE_DISABLED:
			updateSwitchButton(false);
			mWifiListView.setVisibility(View.GONE);
			mTip.setVisibility(View.VISIBLE);
			mLastPoint = null;
			Log.e(TAG, "wifi 已经关闭");
			break;
		}

//		mScaner.pause();
	}

	/**
	 * Shows the latest access points available with supplemental information like
	 * the strength of network and the security for it.
	 */
	private void updateAccessPoints(){
		final int wifiState = mWifiManager.getWifiState();
		switch (wifiState){
			case WifiManager.WIFI_STATE_ENABLED:{
				//连接成功了
				if(mLastPoint != null){
					Log.e(TAG, "已经连接:"+mLastPoint.SSID);
					updateWifiList(mLastPoint);
					updateStatus(getString(R.string.wifi_connected));
				}else if(mConnectingPoint != null) {
				//	Log.e(TAG, "正在连接:"+mConnectingPoint.SSID);
					updateWifiList(mConnectingPoint);
					updateStatus(getString(R.string.wifi_connecting));
				}else {
				//	Log.e(TAG, "没有连接任何wifi点");
					updateWifiList(null);
				}

				break;
			}

			case WifiManager.WIFI_STATE_ENABLING:{
				break;
			}

			case WifiManager.WIFI_STATE_DISABLED:{
				reset();
				break;
			}

			case WifiManager.WIFI_STATE_DISABLING:{
				reset();
				break;
			}
		}
	}

	private void  reset(){
		mLastPoint = null;
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		try{
			TextView tv = (TextView) mConnectDialog.findViewById(R.id.tv_confirm);
			Log.e(TAG, "postion="+position);
			if(mLastPoint != null && position == 0){
				tv.setText(R.string.wifi_disconnect);
				tv.setTag(WifiSettingsActivity.DISCONNECT);
				showConnectDialog(mLastPoint);
			}else if(mConnectingPoint != null){
			//	Toast.makeText(WifiSettingsActivity.this, getString(R.string.wifi_tip_connecting)+mConnectingPoint.SSID, Toast.LENGTH_SHORT).show();
			}else{
				tv.setText(R.string.confirm);
				tv.setTag(WifiSettingsActivity.CONNECT);
				mSelectPoint = new AccessPoint((AccessPoint) adapterView.getAdapter().getItem(position));
				showConnectDialog(mSelectPoint);
				//	Toast.makeText(WifiSettingsActivity.this, "position="+position, Toast.LENGTH_SHORT).show();
			}
		}catch (Exception ex){
			ex.printStackTrace();
		}


	}

	private void showConnectDialog(AccessPoint accessPoint){
		mTVSSID.setText(accessPoint.SSID);
		mETPwd.setText(mSharedPreferencesUtils.getWifiPassword(accessPoint.BSSID));
		mConnectDialog.show();
	}

	private void connectWifi(AccessPoint accessPoint){
		if(WifiUtils.connectWifi(accessPoint)){
			long time = System.currentTimeMillis();
			Log.e(TAG,"开始连接wifi:"+accessPoint.SSID+" time:" + time);
			//将当前的连接清空
			reset();
			mHandler.postDelayed(mTimeOutCallback, WifiSettingsActivity.CONNECT_TIME_OUT);
			mConnectingPoint = accessPoint;
//			saveWifiPassword(mLastPoint.BSSID, pwd);
			updateWifiList(mConnectingPoint);
			updateStatus(getString(R.string.wifi_connecting));
		}else {
		//	Toast.makeText(this, "连接失败", Toast.LENGTH_LONG).show();
		}
	}

	private void disconnect(){
		mWifiManager.disconnect();
		WifiConfiguration configuration = WifiUtils.isConfigExist(mLastPoint.SSID);
		if(configuration != null){
			mWifiManager.removeNetwork(configuration.networkId);
		}
		mLastPoint = null;
		updateWifiList(null);
	//	Toast.makeText(this, "断开wifi", Toast.LENGTH_SHORT).show();
	}

	private void addListHeader(AccessPoint connectPoint){
		mInitHead = true;
		mWifiListView.setHeaderDividersEnabled(true);
		mWifiListView.addHeaderView(mHeadView);
		updateHeader(connectPoint);
	}

	private void removeHeader(){
		if(mWifiListView.getHeaderViewsCount() != 0){
			mWifiListView.removeHeaderView(mHeadView);
			mInitHead = false;
			Log.e(TAG, "找到删除页眉，删除之");
		}
	}

	private void updateHeader(AccessPoint point){
		TextView ssid = (TextView) mHeadView.findViewById(R.id.wifi_ssid);
		ImageView singal = (ImageView) mHeadView.findViewById(R.id.wifi_singal);
		ImageView wifilock = (ImageView) mHeadView.findViewById(R.id.wifi_lock);

		ssid.setText(point.SSID);
	//	Toast.makeText(this, point.toString(), Toast.LENGTH_SHORT).show();
		WifiAdapter.updateSingalIcon(point,singal);
		if(point.isFree()){
			wifilock.setVisibility(View.INVISIBLE);
		}else {
			wifilock.setVisibility(View.VISIBLE);
		}
	}

	/**
	 *
	 * @param accessPoints 集合列表
	 * @param toFilter 需要删除的元素
	 */
	private void filterConnectedPoint(List<AccessPoint> accessPoints, AccessPoint toFilter){
		if(toFilter == null){
			return ;
		}else {
		//	Log.e(TAG, "删除前的size:"+accessPoints.size());
			Iterator<AccessPoint> iter = accessPoints.iterator();
			while (iter.hasNext()){
				AccessPoint point = iter.next();
				if(point.SSID.equals(toFilter.SSID) && point.BSSID.equals(toFilter.BSSID)){
					iter.remove();
				//	Log.e(TAG, "找到相同SSID:"+toFilter.SSID+",删除之");
				}
			}

		//	Log.e(TAG, "删除后的size:"+accessPoints.size());
		}
	}

	private void updateWifiList(AccessPoint filter){
		List<AccessPoint> accessPoints = WifiUtils.parseAccesspoint(mWifiManager.getScanResults());
		//已经连接上,需要删除列表中同名SSID点
		if(filter != null){
		//	Log.e(TAG,"updateWifiList 删除同名点");
			filterConnectedPoint(accessPoints, filter);
			if(!mInitHead){
			//	Log.e(TAG, "添加页眉");
				addListHeader(filter);
			}else {
			//	Log.e(TAG, "更新页眉");
				updateHeader(filter);
			}

		}else {
		//	Log.e(TAG, "没有连接wifi 删除页眉，如果有的话");
			removeHeader();
		}

		mAccessPoints = accessPoints;
		if(mWifiAdapter == null){
			mWifiAdapter = new WifiAdapter(this, mAccessPoints);
			mWifiListView.setAdapter(mWifiAdapter);
		}else {
			mWifiAdapter.updateAccesspoint(mAccessPoints);
		}
		if(mWifiListView.getVisibility() == View.GONE){
			mWifiListView.setVisibility(View.VISIBLE);
		}
	}

	private void updateStatus(String text){
		TextView status = (TextView) mHeadView.findViewById(R.id.wifi_status);
		status.setText(text);
	}
	/**
	 * 保持密码是key用BSSID,不用SSID,SSID不具有唯一性
	 * @param BSSID
	 * @param pwd
	 */
	private void saveWifiPassword(String BSSID, String pwd){
		mSharedPreferencesUtils.setWifiPassword(BSSID, pwd);
	}

	public String getWifiPassword(String BSSID){
		return mSharedPreferencesUtils.getWifiPassword(BSSID);
	}

	Runnable mTimeOutCallback = new Runnable() {
		@Override
		public void run() {
			if(mConnectingPoint != null){
				Toast.makeText(WifiSettingsActivity.this,
							   getString(R.string.wifi_connect)+": "+mConnectingPoint.SSID+" " + getString(R.string.wifi_connect_fail),
							   Toast.LENGTH_LONG).show();
				mConnectingPoint = null;
				updateWifiList(null);
			}
		}
	} ;

//	private  class Scanner extends Handler {
//		private int mRetry = 0;
//
//		Scanner() {
//		}
//
//		void resume() {
//			if (!hasMessages(0)) {
//				sendEmptyMessage(0);
//			}
//		}
//
//		void forceScan() {
//			removeMessages(0);
//			sendEmptyMessage(0);
//		}
//
//		void pause() {
//			mRetry = 0;
//			removeMessages(0);
//		}
//
//		@Override
//		public void handleMessage(Message message) {
//			if (mWifiManager.startScan()) {
//				Log.e(TAG, "start scan wifi");
//			//	updateAccessPoints();
//				mRetry = 0;
//			} else if (++mRetry >= 3) {
//				mRetry = 0;
//				Toast.makeText(WifiSettingsActivity.this, R.string.wifi_fail_to_scan, Toast.LENGTH_LONG).show();
//				return;
//			}
//			sendEmptyMessageDelayed(0, WIFI_RESCAN_INTERVAL_MS);
//		}
//	}

}
